<template>
  <view class="detail-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar">
      <view class="navbar-back" @tap="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="navbar-content">
        <text class="navbar-title">{{ article.title || '文章详情' }}</text>
      </view>
      <view class="navbar-action" @tap="toggleFavorite">
        <text class="iconfont" :class="article.isFavorite ? 'icon-heart-fill' : 'icon-heart'"></text>
      </view>
    </view>

    <!-- 文章头部 -->
    <view class="article-header">
      <image :src="article.cover" class="article-cover" mode="aspectFill"></image>
      <view class="article-info">
        <text class="article-title">{{ article.title }}</text>
        <view class="article-meta">
          <text class="article-category">{{ article.category }}</text>
          <text class="article-date">{{ formatDate(article.publishDate) }}</text>
          <text class="article-views">{{ article.views }}次阅读</text>
        </view>
        <text class="article-summary">{{ article.summary }}</text>
      </view>
    </view>

    <!-- 文章内容 -->
    <scroll-view scroll-y class="article-content">
      <view class="content-section" v-for="(section, index) in article.content" :key="index">
        <text class="section-title" v-if="section.type === 'title'">{{ section.text }}</text>
        <text class="section-text" v-if="section.type === 'paragraph'">{{ section.text }}</text>
        <image v-if="section.type === 'image'" :src="section.src" class="section-image" mode="widthFix"></image>
        <view v-if="section.type === 'quote'" class="section-quote">
          <text class="quote-text">{{ section.text }}</text>
        </view>
        <view v-if="section.type === 'list'" class="section-list">
          <view class="list-item" v-for="(item, i) in section.items" :key="i">
            <text class="list-text">{{ i + 1 }}. {{ item }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 评论区域 -->
    <view class="comments-section" v-if="article.comments && article.comments.length > 0">
      <view class="section-title">评论 ({{ article.comments.length }})</view>
      <view class="comment-item" v-for="comment in article.comments" :key="comment.id">
        <view class="comment-header">
          <view class="comment-author">{{ comment.author }}</view>
          <view class="comment-date">{{ formatDate(comment.date) }}</view>
        </view>
        <view class="comment-content">{{ comment.content }}</view>
        <view class="comment-actions">
          <view class="comment-like" @tap="likeComment(comment)">
            <text class="like-icon">👍</text>
            <text class="like-count">{{ comment.likes }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="action-btn" @tap="toggleFavorite">
        <text class="iconfont" :class="article.isFavorite ? 'icon-heart-fill' : 'icon-heart'"></text>
        <text class="action-text">{{ article.isFavorite ? '已收藏' : '收藏' }}</text>
      </view>
      <view class="action-btn" @tap="shareArticle">
        <text class="iconfont icon-share"></text>
        <text class="action-text">分享</text>
      </view>
      <view class="action-btn" @tap="addComment">
        <text class="iconfont icon-comment"></text>
        <text class="action-text">评论</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      articleId: null,
      article: {
        id: 1,
        title: '如何管理焦虑情绪',
        category: '情绪管理',
        publishDate: '2024-01-15',
        views: 1234,
        summary: '焦虑是现代人常见的情绪问题，学会正确的管理方法可以帮助我们更好地应对生活中的挑战。',
        cover: '/static/article-cover.jpg',
        isFavorite: false,
        content: [
          {
            type: 'title',
            text: '什么是焦虑？'
          },
    
    likeComment(comment) {
      comment.likes += 1
      
      // 保存更新后的评论到本地存储
      try {
        const key = `comments_${this.articleId}`
        uni.setStorageSync(key, this.article.comments)
        
        uni.showToast({
          title: '已点赞',
          icon: 'success',
          duration: 1000
        })
      } catch (e) {
        console.error('点赞失败:', e)
      }
    },
          {
            type: 'paragraph',
            text: '焦虑是一种正常的情绪反应，它帮助我们应对潜在的威胁和挑战。然而，当焦虑变得过度或持续时间过长时，就可能影响我们的日常生活和工作。'
          },
          {
            type: 'title',
            text: '焦虑的常见症状'
          },
          {
            type: 'list',
            items: [
              '心跳加速、出汗',
              '肌肉紧张、颤抖',
              '呼吸急促或困难',
              '注意力难以集中',
              '睡眠质量下降',
              '食欲改变'
            ]
          },
          {
            type: 'title',
            text: '管理焦虑的有效方法'
          },
          {
            type: 'paragraph',
            text: '以下是一些经过科学验证的焦虑管理技巧，可以帮助你更好地应对焦虑情绪：'
          },
          {
            type: 'quote',
            text: '深呼吸是最简单也是最有效的放松技巧之一。当你感到焦虑时，试着进行4-7-8呼吸法：吸气4秒，屏息7秒，呼气8秒。'
          },
          {
            type: 'paragraph',
            text: '除了呼吸练习，规律的运动、充足的睡眠、健康的饮食习惯也都有助于减轻焦虑。如果焦虑症状严重或持续时间较长，建议寻求专业心理咨询师的帮助。'
          },
          {
            type: 'title',
            text: '建立积极的思维模式'
          },
          {
            type: 'paragraph',
            text: '学会识别和挑战消极的思维模式是管理焦虑的重要步骤。当你发现自己陷入担忧的循环时，问问自己：这种担忧是现实的吗？我能控制这种情况吗？有什么积极的解决方案？'
          }
        ]
      },
      comments: [] // 添加评论数组
    }
  },
  
  onLoad(options) {
    if (options.id) {
      this.articleId = options.id
      this.loadArticle()
    } else {
      // 如果没有传入ID，使用默认文章
      this.loadDefaultArticle()
    }
  },
  
  methods: {
    goBack() {
      uni.navigateBack()
    },
    
    loadArticle() {
      try {
        // 从本地存储或API加载文章
        const articles = uni.getStorageSync('articles') || []
        const article = articles.find(a => a.id == this.articleId)
        
        if (article) {
          this.article = article
          this.loadFavoriteStatus()
        } else {
          this.loadDefaultArticle()
        }
        
        // 增加阅读次数
        this.article.views++
        this.saveArticleViews()
        
      } catch (e) {
        console.error('加载文章失败:', e)
        this.loadDefaultArticle()
      }
    },
    
    loadDefaultArticle() {
      // 使用默认文章内容
      this.loadFavoriteStatus()
      
      // 加载评论
        try {
          const commentsKey = `comments_${this.articleId}`
          this.article.comments = uni.getStorageSync(commentsKey) || []
        } catch (e) {
          console.error('加载评论失败:', e)
          this.article.comments = []
        }
        
        this.loading = false
    
    loadFavoriteStatus() {
      try {
        const favorites = uni.getStorageSync('article_favorites') || []
        this.article.isFavorite = favorites.includes(this.article.id)
      } catch (e) {
        console.error('加载收藏状态失败:', e)
      }
    },
    
    toggleFavorite() {
      this.article.isFavorite = !this.article.isFavorite
      this.saveFavoriteStatus()
      
      uni.showToast({
        title: this.article.isFavorite ? '已收藏' : '已取消收藏',
        icon: 'success'
      })
    },
    
    saveFavoriteStatus() {
      try {
        let favorites = uni.getStorageSync('article_favorites') || []
        
        if (this.article.isFavorite) {
          if (!favorites.includes(this.article.id)) {
            favorites.push(this.article.id)
          }
        } else {
          favorites = favorites.filter(id => id !== this.article.id)
        }
        
        uni.setStorageSync('article_favorites', favorites)
        
        // 同时保存到收藏列表
        this.saveToFavoritesList()
        
      } catch (e) {
        console.error('保存收藏状态失败:', e)
      }
    },
    
    saveToFavoritesList() {
      try {
        let favoritesList = uni.getStorageSync('favorites') || []
        
        if (this.article.isFavorite) {
          // 添加到收藏列表
          const favoriteItem = {
            id: this.article.id,
            type: 'article',
            title: this.article.title,
            category: this.article.category,
            cover: this.article.cover,
            summary: this.article.summary,
            addTime: new Date().toISOString()
          }
          
          // 检查是否已存在
          const existingIndex = favoritesList.findIndex(item => 
            item.type === 'article' && item.id === this.article.id
          )
          
          if (existingIndex === -1) {
            favoritesList.unshift(favoriteItem)
          }
        } else {
          // 从收藏列表移除
          favoritesList = favoritesList.filter(item => 
            !(item.type === 'article' && item.id === this.article.id)
          )
        }
        
        uni.setStorageSync('favorites', favoritesList)
        
      } catch (e) {
        console.error('保存到收藏列表失败:', e)
      }
    },
    
    saveArticleViews() {
      try {
        let articles = uni.getStorageSync('articles') || []
        const index = articles.findIndex(a => a.id === this.article.id)
        
        if (index !== -1) {
          articles[index].views = this.article.views
          uni.setStorageSync('articles', articles)
        }
      } catch (e) {
        console.error('保存阅读次数失败:', e)
      }
    },
    
    shareArticle() {
      uni.showActionSheet({
        itemList: ['分享到微信', '分享到朋友圈', '复制链接'],
        success: (res) => {
          switch (res.tapIndex) {
            case 0:
              this.shareToWeChat()
              break
            case 1:
              this.shareToMoments()
              break
            case 2:
              this.copyLink()
              break
          }
        }
      })
    },
    
    shareToWeChat() {
      try {
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneSession',
          type: 0,
          href: '',
          title: this.article.title,
          summary: this.article.summary,
          imageUrl: this.article.cover,
          success: () => {
            uni.showToast({
              title: '分享成功',
              icon: 'success'
            })
          },
          fail: () => {
            uni.showToast({
              title: '分享失败',
              icon: 'error'
            })
          }
        })
      } catch (e) {
        uni.showToast({
          title: '分享功能暂不可用',
          icon: 'none'
        })
      }
    },
    
    shareToMoments() {
      try {
        uni.share({
          provider: 'weixin',
          scene: 'WXSceneTimeline',
          type: 0,
          href: '',
          title: this.article.title,
          summary: this.article.summary,
          imageUrl: this.article.cover,
          success: () => {
            uni.showToast({
              title: '分享成功',
              icon: 'success'
            })
          },
          fail: () => {
            uni.showToast({
              title: '分享失败',
              icon: 'error'
            })
          }
        })
      } catch (e) {
        uni.showToast({
          title: '分享功能暂不可用',
          icon: 'none'
        })
      }
    },
    
    copyLink() {
      uni.setClipboardData({
        data: `情绪大师 - ${this.article.title}`,
        success: () => {
          uni.showToast({
            title: '链接已复制',
            icon: 'success'
          })
        }
      })
    },
    
    addComment() {
      // 简单的评论功能实现
      uni.showModal({
        title: '添加评论',
        editable: true,
        placeholderText: '请输入您的评论...',
        success: (res) => {
          if (res.confirm && res.content) {
            const comment = {
              id: Date.now(),
              content: res.content,
              author: '用户',
              date: new Date().toISOString(),
              likes: 0
            }
            
            // 保存评论到本地存储
            try {
              const key = `comments_${this.articleId}`
              let comments = uni.getStorageSync(key) || []
              comments.unshift(comment)
              uni.setStorageSync(key, comments)
              
              uni.showToast({
                title: '评论成功',
                icon: 'success'
              })
              
              // 重新加载文章以显示新评论
              this.loadArticle()
            } catch (e) {
              uni.showToast({
                title: '评论失败',
                icon: 'error'
              })
            }
          }
        }
      })
    },
    
    likeComment(comment) {
      comment.likes += 1
      
      // 保存更新后的评论到本地存储
      try {
        const key = `comments_${this.articleId}`
        uni.setStorageSync(key, this.article.comments)
        
        uni.showToast({
          title: '已点赞',
          icon: 'success',
          duration: 1000
        })
      } catch (e) {
        console.error('点赞失败:', e)
      }
    },
    
    formatDate(dateString) {
      const date = new Date(dateString)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
    }
  }
}
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 120rpx;
}

/* 自定义导航栏 */
.custom-navbar {
  background: linear-gradient(135deg, var(--primary-color) 0%, var(--secondary-color) 100%);
  padding: 88rpx 40rpx 40rpx;
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-back {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-back .iconfont {
  font-size: 36rpx;
}

.navbar-content {
  flex: 1;
  text-align: center;
  padding: 0 20rpx;
}

.navbar-title {
  font-size: 32rpx;
  font-weight: 600;
}

.navbar-action {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar-action .iconfont {
  font-size: 36rpx;
}

/* 文章头部 */
.article-header {
  background: white;
  margin-bottom: 20rpx;
}

.article-cover {
  width: 100%;
  height: 400rpx;
}

.article-info {
  padding: 40rpx;
}

.article-title {
  font-size: 40rpx;
  font-weight: 600;
  color: var(--text-primary);
  line-height: 1.4;
  display: block;
  margin-bottom: 20rpx;
}

.article-meta {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.article-category {
  font-size: 24rpx;
  color: var(--primary-color);
  background: var(--accent-color);
  padding: 8rpx 16rpx;
  border-radius: 8rpx;
}

.article-date,
.article-views {
  font-size: 24rpx;
  color: var(--text-tertiary);
}

.article-summary {
  font-size: 28rpx;
  color: var(--text-secondary);
  line-height: 1.6;
}

/* 文章内容 */
.article-content {
  background: white;
  padding: 40rpx;
  height: calc(100vh - 700rpx);
}

.content-section {
  margin-bottom: 40rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: 600;
  color: var(--text-primary);
  line-height: 1.4;
  display: block;
  margin-bottom: 20rpx;
}

.section-text {
  font-size: 30rpx;
  color: var(--text-primary);
  line-height: 1.8;
  display: block;
}

.section-image {
  width: 100%;
  border-radius: 12rpx;
  margin: 20rpx 0;
}

.section-quote {
  background: var(--accent-color);
  padding: 30rpx;
  border-radius: 12rpx;
  border-left: 6rpx solid var(--primary-color);
  margin: 20rpx 0;
}

.quote-text {
  font-size: 28rpx;
  color: var(--text-primary);
  line-height: 1.6;
  font-style: italic;
}

.section-list {
  margin: 20rpx 0;
}

.list-item {
  margin-bottom: 15rpx;
}

.list-text {
  font-size: 28rpx;
  color: var(--text-primary);
  line-height: 1.6;
}

/* 评论区域 */
.comments-section {
  background: white;
  margin: 20rpx;
  border-radius: 20rpx;
  padding: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 30rpx;
  padding-bottom: 20rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.comment-item {
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.comment-author {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--primary-color);
}

.comment-date {
  font-size: 24rpx;
  color: #999;
}

.comment-content {
  font-size: 28rpx;
  line-height: 1.6;
  color: #333;
  margin-bottom: 15rpx;
}

.comment-actions {
  display: flex;
  justify-content: flex-end;
}

.comment-like {
  display: flex;
  align-items: center;
  padding: 10rpx 20rpx;
  border-radius: 20rpx;
  background: #f8f9fa;
}

.like-icon {
  font-size: 24rpx;
  margin-right: 8rpx;
}

.like-count {
  font-size: 24rpx;
  color: #666;
}

/* 底部操作栏 */
.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 20rpx 40rpx;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
  padding: 10rpx 20rpx;
}

.action-btn .iconfont {
  font-size: 36rpx;
  color: var(--text-secondary);
}

.action-text {
  font-size: 24rpx;
  color: var(--text-secondary);
}

.action-btn:active {
  opacity: 0.7;
}

/* 图标样式 */
.icon-back::before { content: '←'; }
.icon-heart::before { content: '♡'; }
.icon-heart-fill::before { content: '♥'; color: #ff4757; }
.icon-share::before { content: '↗'; }
.icon-comment::before { content: '💬'; }
</style>